package com.steshov.trainer.service;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

import android.content.ContentResolver;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class Player {

	public static ArrayList<String> getMusicList(
			ContentResolver contentResolver) {
		MediaPlayer mediaPlayer = new MediaPlayer();
		Uri playlistUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		Cursor audioCursor = contentResolver.query(playlistUri, null, null,
				null, null);
		ArrayList<String> songList = new ArrayList<String>();
		while (audioCursor.moveToNext()) {
			int index = audioCursor
					.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
			int pathIndex = audioCursor
					.getColumnIndex(MediaStore.Audio.Media.DATA);
			String name = audioCursor.getString(index);
			String path = audioCursor.getString(pathIndex);
			songList.add(name);

			play(mediaPlayer, path);

		}
		return songList;
	}

	public static void sendMessage(boolean done) {
		Log.i("", String.valueOf(done));
	}

	static private void play(MediaPlayer mediaPlayer, String path) {
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		FileInputStream fis;
		if (!mediaPlayer.isPlaying()) {
			try {
				fis = new FileInputStream(new File(path));
				mediaPlayer.setDataSource(fis.getFD());

				mediaPlayer.prepare();
				mediaPlayer.start();
			} catch (Exception e) {
				Log.e("error", e.getMessage());
			}
		}
	}
}
